package com.study.sfd.person.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.sfd.person.dao.DoctorDao;
import com.study.sfd.person.dao.DoctorPatientRelationDao;
import com.study.sfd.person.dao.DruggistDoctorRelationDao;
import com.study.common.entity.DoctorEntity;
import com.study.sfd.person.entity.DoctorPatientRelationEntity;
import com.study.sfd.person.entity.DruggistDoctorRelationEntity;
import com.study.sfd.person.enums.VerifyStatus;
import com.study.sfd.person.service.DoctorService;
import com.study.sfd.person.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("doctorService")
public class DoctorServiceImpl extends ServiceImpl<DoctorDao, DoctorEntity> implements DoctorService {

    @Autowired
    DruggistDoctorRelationDao druggistDoctorRelationDao;

    @Autowired
    DoctorPatientRelationDao doctorPatientRelationDao;

    @Override
    public List<DoctorEntity> listDoctors()
    {
        Map<String, Object> map = ThreadLocalUtil.get();
        Object id = map.get("druggistId");
        if (id != null) {
            return listByDruggistId((int) id);
        }
        id = map.get("patientId");
        return listByPatientId((int) id);
    }

    public List<DoctorEntity> listByDruggistId(int druggistId)
    {
        List<Integer> doctorIds = druggistDoctorRelationDao.selectList(
                        new LambdaQueryWrapper<DruggistDoctorRelationEntity>()
                                .eq(DruggistDoctorRelationEntity::getDruggistId, druggistId)
                ).stream()
                .map(DruggistDoctorRelationEntity::getDoctorId)
                .collect(Collectors.toList());
        return baseMapper.selectBatchIds(doctorIds);
    }

    public List<DoctorEntity> listByPatientId(int id)
    {
        List<Integer> doctorIds = doctorPatientRelationDao.selectList(
                        new LambdaQueryWrapper<DoctorPatientRelationEntity>()
                                .eq(DoctorPatientRelationEntity::getPatientId, id)
                ).stream()
                .map(DoctorPatientRelationEntity::getDoctorId)
                .collect(Collectors.toList());
        return baseMapper.selectBatchIds(doctorIds);
    }

    @Override
    public DoctorEntity submit(DoctorEntity doctor)
    {
        doctor.setVerifyStatus(VerifyStatus.VERIFYING.getValue());
        baseMapper.updateById(doctor);
        return baseMapper.selectById(doctor.getId());
    }
}